/*
 * Copyright (C) 2009 The Rockchip Android MID Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.highglass.videoplayer;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Parcel;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.storage.StorageEventListener;
import android.os.storage.StorageManager;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnSystemUiVisibilityChangeListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.haijing.highglass.HmdCtrl;
import com.hg.library.config.FParser;
import com.hg.library.utils.InputManager;
import com.hg.library.widget.HaloButton;
import com.highglass.videoplayer.db.HistoryBean;
import com.highglass.videoplayer.db.HistoryBeanInfoDao;
import com.highglass.videoplayer.db.HistoryHttpBean;
import com.highglass.videoplayer.subTitle.SubTitleContent;
import com.highglass.videoplayer.uitl.MediaFile;
import com.highglass.videoplayer.widget.CustomDialog;
import com.highglass.videoplayer.widget.MyGridView;
import com.highglass.videoplayer.widget.StrokeTextView;
import com.lidroid.xutils.ViewUtils;
import com.playmodule.view.PlayView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;


/**
 * 视频播放
 */
public class VideoPlayActivity extends Activity implements
        OnSystemUiVisibilityChangeListener, VideoController.VideoPlayerControl, View.OnClickListener, View.OnFocusChangeListener, PlayView.PlayViewInterface, MediaHelper.AdverInterface {
    TextView time_reminder;
    TextView time_reminder_3d_left;
    TextView time_reminder_3d_right;

    private static final String TAG = "VideoPlayActivity";
    private String mTitle;
    private static final int TIME_LEVEL_1 = 10 * 1000;
    private static final int TIME_LEVEL_2 = 20 * 1000;
    private static final int TIME_LEVEL_3 = 30 * 1000;
    private static final int TIME_LEVEL_4 = 60 * 1000;
    private ViewGroup layout_volume_3d;
    private ImageView ico_volume_3d_left;
    private ImageView ico_volume_3d_right;
    private ImageView ico_volume_3d_left_mid;
    private ImageView ico_volume_3d_right_mid;
    private AudioManager audioManager;
    private int currentVolume = -1;
    private boolean isMuted = false;


    private StorageManager mStorageManager = null;
    private BroadcastReceiver mShutDownReceiver;
    public ProgressView mProgressView;
    public View mPercentView;
    public TextView mPercentText;
    private Uri mUri;
    private boolean mWasPlayingWhenPaused = true;
    private int position = 0;
    /**
     * Called when the activity is first created.
     */
    static StringBuilder mFormatBuilder;
    static Formatter mFormatter;
    private Context mContext;
    private final int SHOWTIME = 2000;
    public static final int FULLSCREEN_FLAG = 0x0003;
    public static final int NOT_FULLSCREEN_FLAG = 0x0004;
    public static final int SHOW_SUBTITLE = 0x0005;
    public static final int HIDE_SUBTITLE = 0x0006;
    public static final int SHOW_PROCESS_FLAG = 0x0007;
    public static final int HIDE_PROCESS_FLAG = 0x0008;
    public static final int SHOW_IMGSUBTITLE = 0x0009;
    public static final int HIDE_IMGSUBTITLE = 0x00010;
    public static final int SHOW_LASTSUBTITLE = 0x00011;
    private static final int TIME_REMIND = 0x00015;
    private static final int VIDEO_STATE = 0x00016;
    public static final int SHOW_INSIDE_SUBTITLE = 0x00017;
    public static final int ADVER_SHOW = 0x00018;
    public static final int MEDIAERROR = 0x00019;
    PowerManager mPowerManager;
    PowerManager.WakeLock mWakeLock;

    public VideoPlayActivity() {
        mContext = this;
    }

    private final int TopView_FADEOUT = 0;
    private VideoPlayActivity mActivity = this;
    public boolean isActivityRunning = true;
    private View mSubtitleView = null;
    private View mSubtitleView_3d = null;
    private HaloButton video_play_activity_full_btn;
    private HaloButton video_play_activity_episode_btn;
    private LinearLayout video_play_detail_ll;
    private LinearLayout video_play_episode_ll;
    private MyGridView video_play_episode_gv;
    private LinearLayout video_play_activity_episode_ll;
    private TextView video_play_name_tv;
    private TextView video_play_age_tv;
    private TextView video_play_duration_tv;
    private TextView video_play_espoise_tv;
    private TextView video_play_director_tv;
    private TextView video_play_actor_tv;
    private TextView video_play_introduction_tv;
    private ImageView video_play_bg;

    public StrokeTextView mSubTitleText = null;
    private StrokeTextView mSubTitleText_3d_left, mSubTitleText_3d_right;

    private ImageView mSubTitleImg = null;
    private ImageView mSubTitleImg_3d_left, mSubTitleImg_3d_right;

    public boolean decodeSubtitleFinish = false;
    public Map<String, List<SubTitleContent>> subtitleList = null;

    private HistoryBeanInfoDao dao;

    HistoryBean iis;
    HistoryHttpBean httpBean;

    private int historyTime = 0;
    private VideoController mVideoController;

    private SubTitleHelper subTitleHelper;
    private MediaHelper mediaHelper;

    private byte state = HmdCtrl.HMD_CTRL_PARAM_DISP_VIDEO_STATE_ON;

    private void updateFullscreenStatus(boolean bUseFullscreen) {
        if (bUseFullscreen) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        } else {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }

    }

    public static boolean isShowingSubtitle = false;

    private boolean isShowSubTitle = false;


    public Handler subtitleHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case SHOW_INSIDE_SUBTITLE:
                    mSubTitleText.setMyText(Html.fromHtml((String) msg.obj));
                    mSubTitleText_3d_left.setMyText(Html.fromHtml((String) msg.obj));
                    mSubTitleText_3d_right.setMyText(Html.fromHtml((String) msg.obj));
                    break;
                case SHOW_LASTSUBTITLE:
                    isShowingSubtitle = false;
                    break;
                case SHOW_SUBTITLE:
                    if (!isShowSubTitle || inSmallSize) {
                        mSubTitleText.setMyText("");
                        mSubTitleText_3d_left.setMyText("");
                        mSubTitleText_3d_right.setMyText("");
                        break;
                    }
                    mSubTitleText.setMyText(Html.fromHtml((String) msg.obj));
                    mSubTitleText_3d_left.setMyText(Html.fromHtml((String) msg.obj));
                    mSubTitleText_3d_right.setMyText(Html.fromHtml((String) msg.obj));
                    isShowingSubtitle = true;
                    // }
                    break;
                case HIDE_SUBTITLE:
                    if (mediaHelper.isPlaying()) {
                        mSubTitleText.setMyText("");
                        mSubTitleText_3d_left.setMyText("");
                        mSubTitleText_3d_right.setMyText("");
                        isShowingSubtitle = false;
                    } else {
                        this.sendEmptyMessageDelayed(HIDE_SUBTITLE, 500L);
                    }
                    break;
                case SHOW_IMGSUBTITLE:
                    mSubTitleImg.setImageBitmap((Bitmap) msg.obj);
                    mSubTitleImg_3d_left.setImageBitmap((Bitmap) msg.obj);
                    mSubTitleImg_3d_right.setImageBitmap((Bitmap) msg.obj);
                    isShowingSubtitle = true;
                    break;
                case HIDE_IMGSUBTITLE:
                    if (mediaHelper.isPlaying()) {
                        mSubTitleImg.setImageBitmap(null);
                        mSubTitleImg_3d_left.setImageBitmap(null);
                        mSubTitleImg_3d_right.setImageBitmap(null);
                        isShowingSubtitle = false;
                    } else {
                        this.sendEmptyMessageDelayed(HIDE_IMGSUBTITLE, 500L);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public Handler progress_Handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_PROCESS_FLAG:
                    mProgressView.showProgress(isInVrMode ? false : isIn3DMode);
                    break;
                case HIDE_PROCESS_FLAG:
                    mProgressView.hideProgress();
                    break;
            }
        }
    };

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                //
                case TopView_FADEOUT:
                    mHandler.removeMessages(SHOWTIME);
                    mHandler.removeMessages(TopView_FADEOUT);
                    break;
                case NOT_FULLSCREEN_FLAG:
                    updateFullscreenStatus(false);
                    break;
                case FULLSCREEN_FLAG:
                    updateFullscreenStatus(true);
                    break;
                case SHOW_PROCESS_FLAG:
                    mProgressView.showProgress(isInVrMode ? false : isIn3DMode);
                    break;
                case HIDE_PROCESS_FLAG:
                    mProgressView.hideProgress();
                    break;
                case TIME_REMIND:
                    mHandler.sendEmptyMessageDelayed(TIME_REMIND, 1000);
                    if (!ten_minute || !one_hour) {
                        if (!ten_minute) {
                            if (mediaHelper.getCurrentPosition() >= 10 * 60 * 1000) {
                                ten_minute = true;
                                File file = getADFile(MediaHelper.TEN_MINUTES);
                                if (file != null && file.exists()) {
                                    mediaHelper.setAdverURI(Uri.fromFile(file), 0);
                                    mode = 0;
                                }
                            }
                        }
                        if (!one_hour) {
                            if (mediaHelper.getCurrentPosition() >= 60 * 60 * 1000) {
                                one_hour = true;
                                File file = getADFile(MediaHelper.ONE_HOUR);
                                if (file != null && file.exists()) {
                                    mediaHelper.setAdverURI(Uri.fromFile(file), 1);
                                    mode = 1;
                                }
                            }
                        }
                    }
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            byte temstate = HmdCtrl.getVideoState();
                            byte mode = HmdCtrl.get3D();
                            Message message = new Message();
                            message.what = VIDEO_STATE;
                            message.arg1 = temstate;
                            message.arg2 = mode;
                            mHandler.sendMessage(message);
                        }
                    }).start();
                    break;
                case VIDEO_STATE:
                    byte temstate = (byte) msg.arg1;
                    if (temstate == HmdCtrl.HMD_CTRL_PARAM_DISP_VIDEO_STATE_OFF && state == HmdCtrl.HMD_CTRL_PARAM_DISP_VIDEO_STATE_ON) {
                        state = temstate;
                        mWasPlayingWhenPaused = mediaHelper.isPlaying();
                        if (mWasPlayingWhenPaused) {
                            mediaHelper.pause();
                        }
                    } else if (temstate == HmdCtrl.HMD_CTRL_PARAM_DISP_VIDEO_STATE_ON && state == HmdCtrl.HMD_CTRL_PARAM_DISP_VIDEO_STATE_OFF) {
                        state = temstate;
                        if (mWasPlayingWhenPaused) {
                            mediaHelper.start();
                        }
                    }
                    break;
                case MEDIAERROR:
                    if (!mediaHelper.isPlaying()) {
                        hideVideoController();
                        hh.removeMessages(1);
                        hh.sendEmptyMessageDelayed(1, 2000);
                        showErrorDialog();
                    }
                    break;
                case ADVER_SHOW:
                    if (msg.arg1 <= 0) {
                        adverRemindMessageVisibility(View.INVISIBLE);
                    } else {
                        adverRemindMessageVisibility(View.VISIBLE);
                        if (mode == 0 && msg.arg2 >= 5) {
                            canCloseAdver = true;
                            adverRemindMessage("广告剩余" + msg.arg1 + "S，" + "按确认键可关闭广告");
                        } else {
                            adverRemindMessage("广告剩余时间：" + msg.arg1 + "S");
                        }
                        msg.arg1 = msg.arg1 - 1;
                        msg.arg2 = msg.arg2 + 1;
                        Message message = new Message();
                        message.copyFrom(msg);
                        sendMessageDelayed(message, 1000);
                    }

                    break;

            }
        }
    };

    public void acquireWakeLock() { // 加锁
        if (mWakeLock != null) {
            try {
                if (mWakeLock.isHeld() == false)
                    mWakeLock.acquire();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Handler hh = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    releaseWakeLock();
                    break;
            }
            super.handleMessage(msg);
        }

    };

    public void releaseWakeLock() { // 解锁
        if (mWakeLock != null) {
            try {
                if (mWakeLock.isHeld()) {
                    mWakeLock.release();
                    mWakeLock.setReferenceCounted(false);
                    // mWakeLock = null;
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public Handler errorDialogHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            onError();
            final CustomDialog localCustomDialog = new CustomDialog(mActivity, R.layout.video_error_dialog, R.style.MyDialogStyle);
            Button localButton1 = (Button) localCustomDialog.findViewById(R.id.btn);
            localButton1.setOnClickListener(new OnClickListener() {
                public void onClick(View paramAnonymousView) {
                    mActivity.Finish();
                }
            });
            localCustomDialog.show();
        }
    };

    private ViewGroup controller = null;

    private PlayView playView = null;
    int mFormatMode = 0;
    int videoMode = -1;
    private boolean isFirstTimeSend3DMessage = true;
    private MyReceiver mReceiver;
    private IntentFilter myFilter;
    private boolean isInVrMode = false;
    private boolean isIn3DMode;
    private boolean isEpisode;
    private int episodeNum = 0;
    private int mode = -1;
    private boolean canCloseAdver = false;
    private boolean initState = false;
    private boolean inSmallSize = true;
    private RelativeLayout play_layout;
    private boolean ten_minute = false;
    private boolean one_hour = false;
    private String movieName;
    private EpisodeAdapter episodeAdapter;
    private String fileFormat;
    private boolean is3DVideo = isIn3DMode;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        this.overridePendingTransition(-1, -1);
        super.onCreate(savedInstanceState);
        this.dao = new HistoryBeanInfoDao(this);
        this.iis = new HistoryBean();
        this.httpBean = new HistoryHttpBean();

        if (mStorageManager == null) {
            mStorageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
            mStorageManager.registerListener(mStorageListener);
        }


        getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(this);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_SHOW_FULLSCREEN);
        getWindow().getDecorView().setBackgroundColor(Color.BLACK);
        setContentView(R.layout.play_display_land);

        ViewUtils.inject(this);

        mSubtitleView = findViewById(R.id.layout_subtitle);
        mSubTitleText = (StrokeTextView) findViewById(R.id.txtsubtitle);
        mSubTitleImg = (ImageView) findViewById(R.id.imgsubtitle);
        mSubTitleText.getPaint().setDither(true);
        mSubTitleText.getPaint().setAntiAlias(true);

        mSubtitleView_3d = findViewById(R.id.layout_subtitle_3d);
        mSubTitleText_3d_left = (StrokeTextView) findViewById(R.id.txtsubtitle_3d_left);
        mSubTitleText_3d_left.getPaint().setDither(true);
        mSubTitleText_3d_left.getPaint().setAntiAlias(true);
        mSubTitleText_3d_right = (StrokeTextView) findViewById(R.id.txtsubtitle_3d_right);
        mSubTitleText_3d_right.getPaint().setDither(true);
        mSubTitleText_3d_right.getPaint().setAntiAlias(true);
        mSubTitleImg_3d_left = (ImageView) findViewById(R.id.imgsubtitle_3d_left);
        mSubTitleImg_3d_right = (ImageView) findViewById(R.id.imgsubtitle_3d_right);
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        final Intent intent = getIntent();
        if (intent == null) {
            return;
        }
        mUri = intent.getData();

        mFormatBuilder = new StringBuilder();
        mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
        movieName = intent.getStringExtra("movieName");
        isInVrMode = intent.getBooleanExtra("isVR", false);
        is3DVideo =  isIn3DMode = intent.getBooleanExtra("is3D", false);
        isEpisode = intent.getBooleanExtra("isEpisode", false);
        if (isEpisode) {
            File parentFile = new File(mUri.getPath()).getParentFile();
            File[] files = parentFile.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (MediaFile.isVideoFileType(MediaFile.getintFileType(files[i].getPath()))) {
                    episodeNum++;
                }
            }
        }
        //----------------------------------------------------------------------------------------->
        layout_volume_3d = (ViewGroup) findViewById(R.id.layout_volume_3d);
        ico_volume_3d_left = (ImageView) layout_volume_3d.findViewById(R.id.ico_volume_3d_left);
        ico_volume_3d_right = (ImageView) layout_volume_3d.findViewById(R.id.ico_volume_3d_right);
        ico_volume_3d_left_mid = (ImageView) layout_volume_3d.findViewById(R.id.ico_volume_3d_left_mid);
        ico_volume_3d_right_mid = (ImageView) layout_volume_3d.findViewById(R.id.ico_volume_3d_right_mid);
        //----------------------------------------------------------------------------------------->
        String name = null;
        try {
            String path = mUri.getPath();
            int index1 = path.lastIndexOf("/");
            int index2 = path.lastIndexOf(".");
            if (index2 < 0) {
                name = path.substring(index1).replace("\"", "").replace("/", "");
            } else {
                name = path.substring(index1, index2).replace("\"", "").replace("/", "");
            }
            mTitle = name;
        } catch (Exception e) {

        }
        subTitleHelper = new SubTitleHelper();
        subTitleHelper.init(mActivity, mTitle);
        mediaHelper = new MediaHelper();
        mediaHelper.setActivity(mActivity, subTitleHelper);
        mediaHelper.setAdverInterface(this);
        controller = (ViewGroup) findViewById(R.id.layout_controller);

        mVideoController = new VideoController(
                VideoPlayActivity.this, controller, name == null ? "" : name + "",
                -1, false);
        mVideoController.setMediaPlayer(this);
        mProgressView = (ProgressView) findViewById(R.id.progress_indicator);
        mPercentView = findViewById(R.id.percent_indicator);
        mPercentView.setVisibility(View.INVISIBLE);
        mPercentText = (TextView) mPercentView.findViewById(R.id.percent_text);
        time_reminder = (TextView) findViewById(R.id.time_reminder);
        time_reminder_3d_left = (TextView) findViewById(R.id.time_reminder_3d_left);
        time_reminder_3d_right = (TextView) findViewById(R.id.time_reminder_3d_right);
        isActivityRunning = true;
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        registShutDownBroadcast();


        position = historyTime;
        playView = (PlayView) findViewById(R.id.playview);
        playView.setSmallWh();
        playView.setActivity(this, mediaHelper);
        try {
            mPowerManager = (PowerManager) mContext
                    .getSystemService(Context.POWER_SERVICE);
            mWakeLock = mPowerManager.newWakeLock(
                    PowerManager.SCREEN_BRIGHT_WAKE_LOCK, TAG);
        } catch (Exception e) {
            e.printStackTrace();
        }
        acquireWakeLock();
        mReceiver = new MyReceiver();
        myFilter = new IntentFilter();
        myFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        myFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        myFilter.addAction("com.ariplane.checkservice.overtime");


        playView.setMode(isInVrMode, mFormatMode);
        mediaHelper.setHistoryTime(historyTime);
        mediaHelper.setVideoURI(mUri, true);

        video_play_activity_full_btn = (HaloButton) findViewById(R.id.video_play_activity_full_btn);
        video_play_activity_episode_btn = (HaloButton) findViewById(R.id.video_play_activity_episode_btn);

        video_play_detail_ll = (LinearLayout) findViewById(R.id.video_play_detail_ll);
        video_play_episode_ll = (LinearLayout) findViewById(R.id.video_play_episode_ll);
        video_play_episode_gv = (MyGridView) findViewById(R.id.video_play_episode_gv);
        video_play_activity_episode_ll = (LinearLayout) findViewById(R.id.video_play_activity_episode_ll);
        play_layout = (RelativeLayout) findViewById(R.id.play_layout);
        video_play_name_tv = (TextView) findViewById(R.id.video_play_name_tv);
        video_play_age_tv = (TextView) findViewById(R.id.video_play_age_tv);
        video_play_duration_tv = (TextView) findViewById(R.id.video_play_duration_tv);
        video_play_espoise_tv = (TextView) findViewById(R.id.video_play_espoise_tv);
        video_play_director_tv = (TextView) findViewById(R.id.video_play_director_tv);
        video_play_actor_tv = (TextView) findViewById(R.id.video_play_actor_tv);
        video_play_introduction_tv = (TextView) findViewById(R.id.video_play_introduction_tv);
        video_play_bg = (ImageView) findViewById(R.id.video_play_bg_iv);
        video_play_detail_ll = (LinearLayout) findViewById(R.id.video_play_detail_ll);
        video_play_episode_ll = (LinearLayout) findViewById(R.id.video_play_episode_ll);
        video_play_episode_gv = (MyGridView) findViewById(R.id.video_play_episode_gv);
        video_play_activity_episode_ll = (LinearLayout) findViewById(R.id.video_play_activity_episode_ll);
        video_play_episode_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (fileFormat != null) {
                    String fileName;
                    if (position < 10) {
                        fileName = "00" + (String) video_play_episode_gv.getAdapter().getItem(position) + fileFormat;
                    } else if (position >= 10 && position < 100) {
                        fileName = "0" + (String) video_play_episode_gv.getAdapter().getItem(position) + fileFormat;
                    } else {
                        fileName = (String) video_play_episode_gv.getAdapter().getItem(position) + fileFormat;
                    }
                    File parentFile = new File(mUri.getPath()).getParentFile();
                    File videoFile = new File(parentFile.getPath()+"/"+fileName);
                    mUri = Uri.fromFile(videoFile);
                    mediaHelper.setVideoURI(mUri, true);
                }
            }
        });

        video_play_activity_full_btn.setScaleNum(4);
        video_play_activity_full_btn.setSpeed(100);
        video_play_activity_full_btn.setLeftMargin(100);

        video_play_activity_episode_btn.setScaleNum(4);
        video_play_activity_episode_btn.setSpeed(100);
        video_play_activity_episode_btn.setLeftMargin(100);

        Drawable full = getResources().getDrawable(R.drawable.full_screen_selector);
        full.setBounds(40, 0, full.getMinimumWidth() + 40, full.getMinimumHeight());
        video_play_activity_full_btn.setCompoundDrawables(full, null, null, null);

        Drawable episode = getResources().getDrawable(R.drawable.movie_episode_selector);
        episode.setBounds(40, 0, episode.getMinimumWidth() + 40, episode.getMinimumHeight());
        video_play_activity_episode_btn.setCompoundDrawables(episode, null, null, null);

        video_play_activity_full_btn.setOnClickListener(this);
        video_play_activity_full_btn.setOnFocusChangeListener(this);

        video_play_activity_episode_btn.setOnClickListener(this);
        video_play_activity_episode_btn.setOnFocusChangeListener(this);

        video_play_name_tv.setText(movieName + "");
        video_play_activity_full_btn.setFocusableInTouchMode(true);
        video_play_activity_full_btn.setFocusable(true);
        video_play_activity_full_btn.requestFocus();
//        isEpisode = true;
//        episodeNum = 10;
        if (isEpisode && episodeNum > 0) {
            video_play_activity_episode_btn.setVisibility(View.VISIBLE);
            video_play_activity_episode_ll.setVisibility(View.VISIBLE);
            video_play_espoise_tv.setVisibility(View.VISIBLE);
            video_play_espoise_tv.setText("集数：" + episodeNum);
            video_play_duration_tv.setVisibility(View.GONE);
            episodeAdapter = new EpisodeAdapter(this);
            video_play_episode_gv.setAdapter(episodeAdapter);
            List<String> strings = new ArrayList<>();
            for (int i = 1; i < episodeNum + 1; i++) {
                strings.add(i + "");
            }
            episodeAdapter.setList(strings);
            episodeAdapter.notifyDataSetChanged();
            fileFormat = getFileFormat();
        }
        getDetails();
    }

    StorageEventListener mStorageListener = new StorageEventListener() {
        @Override
        public void onStorageStateChanged(String path, String oldState,
                                          String newState) {

            if (mUri != null) {
                String[] media_path = mUri.toString().split("/");
                String[] arg_path = path.split("/");
                if (arg_path[2].equals(media_path[2])) {
                    mediaHelper.stopPlayback();
                    finish();
                }
            }
        }
    };

    private void registShutDownBroadcast() {
        mShutDownReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (action.equals(Intent.ACTION_SHUTDOWN)) {
                    mediaHelper.stopPlayback();
                    finish();
                }
            }
        };
        registerReceiver(mShutDownReceiver, new IntentFilter(
                Intent.ACTION_SHUTDOWN));
    }


    @Override
    public void onPause() {
        this.overridePendingTransition(-1, -1);
        super.onPause();
        int duration = 0;
        isActivityRunning = false;
        mWasPlayingWhenPaused = mediaHelper.isPlaying();
        duration = mediaHelper.getDuration();
        historyTime = position = mediaHelper.getCurrentPosition();
        playView.onPause();
        mediaHelper.pause();
        insertHisrecord(duration, position);

        progress_Handler.removeMessages(SHOW_PROCESS_FLAG);
        progress_Handler.removeMessages(HIDE_PROCESS_FLAG);
        unregisterReceiver(mReceiver);
        mHandler.removeMessages(TIME_REMIND);
        HmdCtrl.set3D(HmdCtrl.HMD_CTRL_PARAM_DISP_3D_NONE);
        HmdCtrl.openVR(0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.video_play_activity_full_btn:
                playView.setFullSize();
                break;
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.video_play_activity_full_btn:
                video_play_episode_ll.setVisibility(View.GONE);
                video_play_detail_ll.setVisibility(View.VISIBLE);
                break;
            case R.id.video_play_activity_episode_btn:
                video_play_episode_ll.setVisibility(View.VISIBLE);
                video_play_detail_ll.setVisibility(View.GONE);
                break;
        }
    }

    public void insertHisrecord(int duration, int position) {
        if (mUri.toString().contains("http://")) {
            return;
        }
        if (position == 0 || duration == 0) {
            return;
        }
        try {
            if (!mUri.toString().contains("http://")) {
                String path = mUri.getPath();
                int index1 = path.lastIndexOf("/");
                String title = path.substring(index1).replace("\"", "").replace("/", "");
                File file = new File(path);
                long size = 0;
                if (file != null) {
                    size = file.length();
                }
                this.iis.duration = duration;
                this.iis.playTime = position;
                this.iis.path = mUri.getPath();
                this.iis.size = "" + size;
                this.iis.casts = "";
                this.iis.directors = "";
                this.iis.title = title;
                this.iis.type = "";
                this.iis.genres = "";
                this.iis.images = "none";
                this.iis.value = "";
                this.iis.writers = "";
                this.iis.summary = "";
                this.iis.inTime = System.currentTimeMillis();

                // TODO: 2015/12/1  保存数据
                this.dao.insertToDB(this.iis);
            }
        } catch (Exception e) {
        }
    }

    private void sendHistoryRecord(HistoryBean bean) {
        Intent intent = new Intent("android.intent.action.history_action");
        intent.putExtra("path", bean.path);
        intent.putExtra("duration", bean.duration);
        intent.putExtra("historyTime", bean.playTime);
        intent.putExtra("imageURL", bean.images);
        intent.putExtra("name", mTitle);
        sendBroadcast(intent);

    }

    @Override
    public void onResume() {
        super.onResume();
        isActivityRunning = true;
        registerReceiver(mReceiver, myFilter);
        playView.onResume();
        if (mediaHelper.getAderPlayingState()) {
            mediaHelper.start();
        } else {
            if (mWasPlayingWhenPaused) {
                mediaHelper.start();
            } else {
                mediaHelper.pause();
            }
        }
        int curmode = 1;
        if (inSmallSize) {
            HmdCtrl.set3D(HmdCtrl.HMD_CTRL_PARAM_DISP_3D_NONE);
            curmode = 1;
        } else {
            if (isIn3DMode) {
                HmdCtrl.set3D(HmdCtrl.HMD_CTRL_PARAM_DISP_3D_HALF_LR);
                curmode = 2;
            } else {
                HmdCtrl.set3D(HmdCtrl.HMD_CTRL_PARAM_DISP_3D_NONE);
                curmode = 1;
            }
        }
        try {
            IBinder flinger = ServiceManager.getService("SurfaceFlinger");
            if (flinger != null) {
                Parcel data = Parcel.obtain();
                data.writeInterfaceToken("android.ui.ISurfaceComposer");
                data.writeInt(curmode); // 1:2D content, 2:3D content.
                data.writeFloat(0.95f); // scale, default 0.95
                flinger.transact(1017, data, null, 0);
                data.recycle();
            }
        } catch (RemoteException ex) {
        }
        mHandler.sendEmptyMessage(TIME_REMIND);
    }

    public void sendRemindMessage() {
        mHandler.removeMessages(TIME_REMIND);
        mHandler.sendEmptyMessageDelayed(TIME_REMIND, 2000);
    }

    @Override
    public void setInSmallSize(boolean inSmallSize) {
        this.inSmallSize = inSmallSize;
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) play_layout.getLayoutParams();
        if (inSmallSize) {
            lp.width = 581;
            lp.height = 346;
            lp.setMargins(324, 95, 0, 0);
        } else {
            lp.width = 1920;
            lp.height = 1080;
            lp.setMargins(0, 0, 0, 0);
        }
        play_layout.setLayoutParams(lp);
        if (mVideoController.isShowing()) {
            mVideoController.hide();
        }
        int curmode = 1;
        if (inSmallSize) {
            set3DMode(false, -1);
            HmdCtrl.set3D(HmdCtrl.HMD_CTRL_PARAM_DISP_3D_NONE);
            curmode = 1;
        } else {
            if (is3DVideo) {
                set3DMode(true, 1);
                HmdCtrl.set3D(HmdCtrl.HMD_CTRL_PARAM_DISP_3D_HALF_LR);
                curmode = 2;
            } else {
                set3DMode(false, 0);
                HmdCtrl.set3D(HmdCtrl.HMD_CTRL_PARAM_DISP_3D_NONE);
                curmode = 1;
            }
        }
        try {
            IBinder flinger = ServiceManager.getService("SurfaceFlinger");
            if (flinger != null) {
                Parcel data = Parcel.obtain();
                data.writeInterfaceToken("android.ui.ISurfaceComposer");
                data.writeInt(curmode); // 1:2D content, 2:3D content.
                data.writeFloat(0.95f); // scale, default 0.95
                flinger.transact(1017, data, null, 0);
                data.recycle();
            }
        } catch (RemoteException ex) {
        }
    }

    public void init3DState() {
        if (initState) {
            return;
        }
        initState = true;
        if (videoMode == -1) {
            if (is3DVideo(mUri)) {
                mFormatMode = 1;
                set3DMode(true, mFormatMode);
            } else {
                mFormatMode = 0;
                set3DMode(false, mFormatMode);
            }
        } else {
            switch (videoMode) {
                case 0:
                    mFormatMode = 0;
                    set3DMode(false, mFormatMode);
                    break;
                case 1:
                    mFormatMode = 1;
                    set3DMode(true, mFormatMode);
                    break;
            }
        }
    }

    public void send3DMessage() {
        mHandler.removeMessages(TIME_REMIND);
        if (isIn3DMode) {
            HmdCtrl.set3D(HmdCtrl.HMD_CTRL_PARAM_DISP_3D_HALF_LR);
        } else {
            HmdCtrl.set3D(HmdCtrl.HMD_CTRL_PARAM_DISP_3D_NONE);
        }
        mHandler.sendEmptyMessageDelayed(TIME_REMIND, 2000);
    }

    public boolean getWasPlayingWhenPaused() {
        return mWasPlayingWhenPaused;
    }

    @Override
    protected void onStart() {
        ((AudioManager) getSystemService(AUDIO_SERVICE)).requestAudioFocus(
                null, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
        super.onStart();
    }

    @Override
    public void onStop() {

        super.onStop();
        subtitleHandler.removeMessages(VideoPlayActivity.HIDE_IMGSUBTITLE);
        subtitleHandler.removeMessages(VideoPlayActivity.HIDE_SUBTITLE);
        subtitleHandler.removeMessages(VideoPlayActivity.SHOW_SUBTITLE);
        subtitleHandler.removeMessages(VideoPlayActivity.SHOW_IMGSUBTITLE);
        mediaHelper.setshowSubTitleFlag(false);
        hh.removeMessages(1);
        hh.sendEmptyMessageDelayed(1, 2000);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        unregisterReceiver(mShutDownReceiver);
        isActivityRunning = false;
        Intent intentm = new Intent("android.rk.RockVideoPlayer.state.stop");
        intentm.putExtra("msg", "android.rk.RockVideoPlayer.state.stop");
        sendBroadcast(intentm);
    }

    public boolean onError() {
        mHandler.removeCallbacksAndMessages(null);
        mProgressView.showProgress(isInVrMode ? false : isIn3DMode);
        return false;
    }

    public void Finish() {
        finish();
    }

    public void setUri(Uri uri) {
        init();
        mUri = uri;
        mHandler.removeMessages(TIME_REMIND);
    }

    private void init() {
        initState = false;
    }

    public void dismissLoading() {
        mProgressView.showProgress(isInVrMode ? false : isIn3DMode);
        mPercentView.setVisibility(View.INVISIBLE);

    }

    Handler dismissVolumeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    layout_volume_3d.setVisibility(View.GONE);
                    break;
            }
        }
    };

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_UP) {
            if (!inSmallSize) {
                if (mediaHelper.isPlaying()) {
                    pause();
                } else {
                    start();
                }
                mVideoController.show();
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (!inSmallSize && event.getAction() == KeyEvent.ACTION_DOWN && (InputManager.handledEnterKeyEvent(event.getKeyCode()))) {
            if (mediaHelper.getAderPlayingState()) {
                if (mode == 0 && canCloseAdver) {
                    mediaHelper.closeAdver();
                }
                return true;
            }
            if (mediaHelper.isPlaying()) {
                pause();
            } else {
                start();
            }
            mVideoController.show();
            return true;
        }
        if (isIn3DMode) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
                    dismissVolumeHandler.removeMessages(0);
                    layout_volume_3d.setVisibility(View.VISIBLE);
                    dismissVolumeHandler.sendEmptyMessageDelayed(0, 3000);
                    audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, 0);
                    currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                    isMuted = false;
                    if (Build.VERSION.SDK_INT >= 23) {
                        isMuted = audioManager.isStreamMute(AudioManager.STREAM_MUSIC);
                    }
                    if (isMuted || currentVolume < -1) {
                        currentVolume = -1;
                    }
                    switch (currentVolume) {
                        case -1:
                            ico_volume_3d_left.setVisibility(View.GONE);
                            ico_volume_3d_right.setVisibility(View.GONE);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_off);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_off);
                            break;
                        case 0:
                            ico_volume_3d_left.setVisibility(View.GONE);
                            ico_volume_3d_right.setVisibility(View.GONE);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_off);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_off);
                            break;
                        case 1:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_1);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_1);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on_1);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on_1);
                            break;
                        case 2:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_2);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_2);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on_1);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on_1);
                            break;
                        case 3:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_3);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_3);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on_1);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on_1);
                            break;
                        case 4:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_4);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_4);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on_1);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on_1);
                            break;
                        case 5:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_5);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_5);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on_1);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on_1);
                            break;
                        case 6:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_6);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_6);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on_1);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on_1);
                            break;
                        case 7:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_7);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_7);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on_1);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on_1);
                            break;
                        case 8:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_8);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_8);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                        case 9:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_9);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_9);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                        case 10:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_10);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_10);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                        case 11:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_11);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_11);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                        case 12:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_12);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_12);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                        case 13:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_13);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_13);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                        case 14:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_14);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_14);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                        case 15:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_15);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_15);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                        case 16:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_16);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_16);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                    }
                    return true;
                } else if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
                    dismissVolumeHandler.removeMessages(0);
                    layout_volume_3d.setVisibility(View.VISIBLE);
                    dismissVolumeHandler.sendEmptyMessageDelayed(0, 3000);
                    audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, 0);
                    currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                    isMuted = false;
                    if (Build.VERSION.SDK_INT >= 23) {
                        isMuted = audioManager.isStreamMute(AudioManager.STREAM_MUSIC);
                    }
                    if (currentVolume > 16) {
                        currentVolume = 16;
                    }
                    if (isMuted) {
                        currentVolume = -1;
                    }
                    switch (currentVolume) {
                        case -1:
                            ico_volume_3d_left.setVisibility(View.GONE);
                            ico_volume_3d_right.setVisibility(View.GONE);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_off);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_off);
                            break;
                        case 0:
                            ico_volume_3d_left.setVisibility(View.GONE);
                            ico_volume_3d_right.setVisibility(View.GONE);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_off);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_off);
                            break;
                        case 1:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_1);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_1);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on_1);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on_1);
                            break;
                        case 2:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_2);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_2);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on_1);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on_1);
                            break;
                        case 3:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_3);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_3);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on_1);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on_1);
                            break;
                        case 4:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_4);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_4);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on_1);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on_1);
                            break;
                        case 5:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_5);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_5);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on_1);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on_1);
                            break;
                        case 6:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_6);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_6);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on_1);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on_1);
                            break;
                        case 7:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_7);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_7);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on_1);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on_1);
                            break;
                        case 8:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_8);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_8);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                        case 9:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_9);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_9);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                        case 10:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_10);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_10);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                        case 11:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_11);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_11);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                        case 12:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_12);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_12);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                        case 13:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_13);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_13);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                        case 14:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_14);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_14);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                        case 15:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_15);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_15);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                        case 16:
                            ico_volume_3d_left.setVisibility(View.VISIBLE);
                            ico_volume_3d_right.setVisibility(View.VISIBLE);
                            ico_volume_3d_left.setImageResource(R.drawable.volume_16);
                            ico_volume_3d_right.setImageResource(R.drawable.volume_16);
                            ico_volume_3d_left_mid.setImageResource(R.drawable.volume_on);
                            ico_volume_3d_right_mid.setImageResource(R.drawable.volume_on);
                            break;
                    }
                    return true;
                }
            }
            return super.dispatchKeyEvent(event);
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (inSmallSize) {
            return super.onKeyDown(keyCode, event);
        } else {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                playView.setSmallSize(false);
                return true;
            }
            if (mediaHelper.getAderPlayingState()) {
                if (InputManager.handledEnterKeyEvent(keyCode)) {
                    if (mode == 0 && canCloseAdver) {
                        mediaHelper.closeAdver();
                    }
                }
                return true;
            }
            if (mediaHelper.isPrepare()
                    &&
                    keyCode != KeyEvent.KEYCODE_SEARCH
                    && keyCode != KeyEvent.KEYCODE_CALL
                    && keyCode != KeyEvent.KEYCODE_ENDCALL
                    && mVideoController != null
                    ) {
                if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK
                        || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
                    if (mediaHelper.isPlaying()) {
                        pause();
                        mVideoController.show();
                    } else {
                        start();
                        mVideoController.hide();
                    }
                    return true;
                } else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP
                        && mediaHelper.isPlaying()) {
                    pause();
                    mVideoController.show();
                } else if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY) {
                    start();
                    return true;
                } else if (keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE) {
                    pause();
                    return true;
                } else if (InputManager.handledEnterKeyEvent(keyCode)) {
                    if (mediaHelper.isPlaying()) {
                        pause();
                    } else {
                        start();
                    }
                    mVideoController.show();
                    return true;
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                    position = mediaHelper.getCurrentPosition() - getTime();
                    mediaHelper.seekTo(position);
                    mVideoController.show();
                    return true;
                } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                    position = mediaHelper.getCurrentPosition() + getTime();
                    mediaHelper.seekTo(position);
                    mVideoController.show();
                    return true;
                } else if (keyCode == KeyEvent.KEYCODE_MENU) {
                    mVideoController.hide();
                    return super.onKeyDown(keyCode, event);
                }
            }
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public void onSystemUiVisibilityChange(int arg0) {
        // TODO Auto-generated method stub
        if (arg0 != View.SYSTEM_UI_FLAG_SHOW_FULLSCREEN) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_SHOW_FULLSCREEN);
        }

    }

    //2d 3d 切换
    private void set3DMode(boolean is3D, int type) {
        Intent intentToFramework = new Intent("player.3DMode");
        intentToFramework.putExtra("is3DMode", is3D);
        sendBroadcast(intentToFramework);
        mVideoController.setIs3DFormat(is3D);
        if (is3D) {
            isIn3DMode = true;
            mSubtitleView.setVisibility(View.GONE);
            mSubtitleView_3d.setVisibility(View.VISIBLE);
        } else {
            isIn3DMode = false;
            mSubtitleView.setVisibility(View.VISIBLE);
            mSubtitleView_3d.setVisibility(View.GONE);
        }
    }

    //检测是否为3d文件
    private boolean is3DVideo(Uri uri) {
        String path = uri.getPath();

        File file = new File(path);
        if (file.exists()) {
            path = file.getName();
        } else {
            return false;
        }
        if (path.contains("3D") || path.contains("3d") || path.contains("HSBS")
                || path.contains("hsbs") || path.contains("Half-SBS")
                || path.contains("half_sbs")) {
            return true;
        } else {
            return false;
        }
    }


    /*    显示  关闭字幕    */
    private void showSubTitle() {
        isShowSubTitle = true;
    }

    public void hideSubTitle() {
        isShowSubTitle = false;
    }

    public static final int SINGLE_PLAY = 0;
    public static final int SINGLE_CYCLE = 1;
    public static final int SEQUENTIAL_PLAY = 2;
    public static final int LIST_LOOP = 3;

    public String stringForTime(int timeMs) {
        int totalSeconds = timeMs / 1000;

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60);

        mFormatBuilder.setLength(0);
        if (minutes >= 100) {
            return mFormatter.format("%03d:%02d", minutes, seconds).toString();
        }
        return mFormatter.format("%02d:%02d", minutes, seconds).toString();
    }

    @Override
    public int getBrightMode() {
        return 0;
    }

    public void start() {
        mediaHelper.start();
    }

    @Override
    public void pause() {
        mediaHelper.pause();
    }

    @Override
    public int getDuration() {
        if (isActivityRunning) {
            return mediaHelper.getDuration();
        } else {
            return 0;
        }
    }

    @Override
    public int getCurrentPosition() {
        if (isActivityRunning) {
            return mediaHelper.getCurrentPosition();
        } else {
            return 0;
        }

    }

    @Override
    public void seekTo(int pos) {
        mediaHelper.seekTo(pos);
    }

    @Override
    public boolean isPlaying() {
        return mediaHelper.isPlaying();
    }

    @Override
    public int getBufferPercentage() {
        return mediaHelper.getBufferPercentage();
    }

    @Override
    public int getVolumeMode() {
        return 0;
    }

    @Override
    public void onAdverComplete() {
        mHandler.removeMessages(ADVER_SHOW);
        adverRemindMessageVisibility(View.INVISIBLE);
        canCloseAdver = false;
        if (mode != MediaHelper.END) {
            mediaHelper.setVideoURI(mUri, true);
        }
        mode = -1;
    }

    @Override
    public void onAdverStart(int duration) {
        if (mode == 2) {
            return;
        }
        hideVideoController();
        Message message = new Message();
        message.what = ADVER_SHOW;
        message.arg1 = duration;
        message.arg2 = 0;
        mHandler.sendMessage(message);
    }

    @Override
    public void onVideoComplete() {
        if (!isInVrMode) {
            acquireWakeLock();
            File file = getADFile(MediaHelper.END);
            if (file != null && file.exists()) {
                mediaHelper.setAdverURI(Uri.fromFile(file), 2);
                mode = 2;
            }
        }
    }

    public void showVideoController() {
        mVideoController.show();
    }

    public void hideVideoController() {
        if (mediaHelper.getAderPlayingState()) {
            return;
        }
        mVideoController.hide();
    }

    public void setTitle(String title) {
        mVideoController.setTitle(title);
        mTitle = title;
        subTitleHelper.init(mActivity, mTitle);
    }


    /* 在前5s内以10s、20s、30s、1min、5min为步长逐步快进，在5s后稳定在5min的步长 */
    private long press_key_time = 0;
    private long press_key_time_record = 0;

    private int getTime() {
        long curren_time = System.currentTimeMillis();
        if (curren_time - press_key_time > 200) {
            press_key_time_record = press_key_time = curren_time;
            return TIME_LEVEL_1;
        }
        if (curren_time - press_key_time < 200) {
            press_key_time = curren_time;
            if (curren_time - press_key_time_record < 1000) {
                return TIME_LEVEL_1;
            }
            if (1000 <= curren_time - press_key_time_record && curren_time - press_key_time_record < 2000) {
                return TIME_LEVEL_2;
            }
            if (2000 <= curren_time - press_key_time_record && curren_time - press_key_time_record < 3000) {
                return TIME_LEVEL_3;
            }
            if (3000 <= curren_time - press_key_time_record) {
                return TIME_LEVEL_4;
            }
        }
        return 0;
    }

    public IBinder getwindowtoken() {
        return playView.getWindowToken();
    }

    public boolean canPlay() {
        return playView.canPlay();
    }

    private void showErrorDialog() {
        if (!isActivityRunning) {
            return;
        }
        final CustomDialog localCustomDialog = new CustomDialog(mActivity, R.layout.video_error_dialog, R.style.MyDialogStyle);
        Button localButton1 = (Button) localCustomDialog.findViewById(R.id.btn);
        localButton1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View paramAnonymousView) {
                mActivity.Finish();
            }
        });
        localCustomDialog.show();
        localCustomDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    mActivity.finish();
                }
                return false;
            }
        });
    }

    private class MyHomeKeyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            mediaHelper.StopPlay();
            finish();
        }
    }

    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                if (mVideoController != null) {
                    mVideoController.getBatteryStatus(intent);
                }
            } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                mediaHelper.StopPlay();
                finish();
            } else if ("com.ariplane.checkservice.overtime".equals(action)) {
                if (mediaHelper.isPlaying()) {
                    mediaHelper.pause();
                }
            }
        }
    }

    private void adverRemindMessage(String message) {
        time_reminder_3d_left.setText(message);
        time_reminder_3d_right.setText(message);
        time_reminder.setText(message);
    }

    private void adverRemindMessageVisibility(int flag) {
        if (isIn3DMode) {
            time_reminder_3d_left.setVisibility(flag);
            time_reminder_3d_right.setVisibility(flag);
        } else {
            time_reminder.setVisibility(flag);
        }
    }

    private File getADFile(int mode) {
        if (isInVrMode) {
            return null;
        }
        if (isEpisode && mode == MediaHelper.ONE_HOUR) {
            return null;
        }
        File adFolder;
        if (isIn3DMode) {
            adFolder = new File(FParser.BASE_PATH+"ads/movie/3D");
        } else {
            adFolder = new File(FParser.BASE_PATH+"ads/movie/2D");
        }
        return getADFileByMode(adFolder, mode);
    }

    private File getADFileByMode(File folder, int mode) {
        if (folder == null || !folder.exists()) {
            return null;
        }
        File modeFolder = null;
        switch (mode) {
            case 0:
                modeFolder = new File(folder.getPath() + "/10min");
                break;
            case 1:
                modeFolder = new File(folder.getPath() + "/1h");
                break;
            case 2:
                modeFolder = new File(folder.getPath() + "/end");
                break;
        }
        if (modeFolder != null && modeFolder.exists()) {
            File[] files = modeFolder.listFiles();
            if (files != null && files.length > 0) {
                Random rand = new Random();
                int randNum = rand.nextInt(files.length);
                return files[randNum];
            }

        }
        return null;
    }

    private void getDetails() {
        File file = new File(mUri.getPath());
        if (file.exists()) {
            File parent = file.getParentFile();
            File descreption = new File(parent.getPath() + "/description.txt");
            if (descreption.exists()) {
                try {
                    FileInputStream inputStream = new FileInputStream(descreption);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"GB2312"));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (line.startsWith("year:")) {
                            video_play_age_tv.setText(getString(R.string.movie_age)+line.substring(5));
                        } else if (line.startsWith("duration:")) {
                            video_play_duration_tv.setText(getString(R.string.movie_duration)+line.substring(9));
                        } else if (line.startsWith("director:")) {
                            video_play_director_tv.setText(getString(R.string.movie_director)+line.substring(9));
                        } else if (line.startsWith("actors:")) {
                            video_play_actor_tv.setText(getString(R.string.movie_actor)+line.substring(7));
                        } else if (line.startsWith("description:")) {
                            video_play_introduction_tv.setText(line.substring(12));
                        }
                    }
                } catch (FileNotFoundException e) {
                } catch (IOException e) {
                }

            }
        } else {
            Log.e("fuck you", "file null");
        }
    }

    private String getFileFormat() {
        if (mUri != null) {
            String path = mUri.getPath();
            int index1 = path.lastIndexOf(".");
            if (index1 != 0 && index1 != path.length()) {
                String fileFormat = path.substring(index1);
                return fileFormat;
            }
        }
        return null;
    }
}
